//
//  CLViewModel.m
//  CLBrowser
//
//  Created by chuck on 2021/7/8.
//

#import "CLViewModel.h"
/// MVVM View
/// The base map of 'params'
/// The `params` parameter in `-initWithParams:` method.
/// Key-Values's key
/// 传递唯一ID的key：例如：商品id 用户id...
NSString *const CLViewModelIDKey = @"CLViewModelIDKey";
/// 传递导航栏title的key：例如 导航栏的title...
NSString *const CLViewModelTitleKey = @"CLViewModelTitleKey";
/// 传递数据模型的key：例如 商品模型的传递 用户模型的传递...
NSString *const CLViewModelUtilKey = @"CLViewModelUtilKey";
/// 传递webView Request的key：例如 webView request...
NSString *const CLViewModelRequestKey = @"CLViewModelRequestKey";
@interface CLViewModel ()

/// 整个应用的服务层 The `services` parameter in `-initWithServices:params` method.
@property (nonatomic, strong, readwrite) id<CLViewModelServices> services;
/// The `params` parameter in `-initWithServices:params` method.
@property (nonatomic, readwrite, copy) NSDictionary *params;
/// A RACSubject object, which representing all errors occurred in view model.
@property (nonatomic, readwrite, strong) RACSubject *errors;
/// The `View` willDisappearSignal
@property (nonatomic, readwrite, strong) RACSubject *willDisappearSignal;

@property (nonatomic, strong) id objObserver;

@property (nonatomic, strong) NSMutableDictionary * dictCommand;
@end
@implementation CLViewModel

/// when `BaseViewModel` created and call `initWithParams` method , so we can ` initialize `
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    CLViewModel *viewModel = [super allocWithZone:zone];
    @weakify(viewModel)
    [[viewModel
      rac_signalForSelector:@selector(initWithServices:params:)]
     subscribeNext:^(id x) {
         @strongify(viewModel)
         [viewModel initialize];
     }];
    return viewModel;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.services = CLNavigationService;
    }
    return self;
}
- (instancetype)initWithParams:(NSDictionary *)params {
    return [self initWithServices:CLNavigationService params:params];
}
/// create `viewModel` instance
- (instancetype)initWithServices:(id<CLViewModelServices>)services params:(NSDictionary *)params {
    self = [super init];
    if (self) {
        /// 默认在viewDidLoad里面加载本地和服务器的数据
        self.shouldFetchLocalDataOnViewModelInitialize = YES;
        self.shouldRequestRemoteDataOnViewDidLoad = YES;
        /// 允许IQKeyboardMananger接管键盘弹出事件
        self.keyboardEnable = YES;
        self.shouldResignOnTouchOutside = YES;
        self.keyboardDistanceFromTextField = 10.0f;
        self.prefersNavigationBarBottomLineHidden = YES;
        self.title = StrNilHolder(params[CLViewModelTitleKey], @"");
        /// 赋值
        self.services = services;
        self.params   = params;
    }
    return self;
}


- (RACSubject *)errors {
    if (!_errors) _errors = [RACSubject subject];
    return _errors;
}

- (RACSubject *)willDisappearSignal {
    if (!_willDisappearSignal) _willDisappearSignal = [RACSubject subject];
    return _willDisappearSignal;
}

/// sub class can override
- (void)initialize {}

/// 监听刷新
- (void)addObserverForUpdatedBlock:(void (^)(id object,NSString * key))block{
    [Notifier addObserverForName:NSStringFromClass(self.class) object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        NSDictionary * p = note.object;
        !block?:block(p[@"object"],p[@"key"]);
    }];
}
/// 通知同类数据更新数据，刷新界面
- (void)postModelUpdatedNotificationWithObject:(id)object forKey:(NSString *)key{
    NSMutableDictionary * p = [NSMutableDictionary dictionary];
    [p cl_setObjectSafe:object forKey:@"object"];
    [p cl_setObjectSafe:key forKey:@"key"];
    [Notifier postNotificationName:NSStringFromClass(self.class) object:p userInfo:nil];
}
- (void)dealloc {
//    CLDealloc;
    if (self.objObserver) {
        [Notifier removeObserver:self.objObserver];
        self.objObserver = nil;
    }
}
- (void)setRacCommand:(RACCommand*)racCommand forKey:(NSString *)key {
    [self.dictCommand cl_setObjectSafe:racCommand forKey:key];
}
- (RACCommand *)racCommandForKey:(NSString *)key {
    return [self.dictCommand objectForKey:key];
}
- (NSMutableDictionary *)dictCommand {
    if (!_dictCommand) {
        _dictCommand = [NSMutableDictionary dictionary];
    }
    return _dictCommand;
}
@end
